//
//  AppDelegate.m
//  us
//
//  Created by 李鹏程 on 2025/3/26.
//

#import "AppDelegate.h"

#import <UMCommon/UMCommon.h>
#import "LoginViewController.h"
#import "IQKeyboardManager.h"
#import "USEaseIMHelper.h"
#import <QCloudCOSXML/QCloudCOSXMLTransfer.h>
#import <JPUSHService.h>
#import <UserNotifications/UserNotifications.h>
#import <WXApi.h>
#import "SceneDelegate.h"

@interface AppDelegate ()<QCloudSignatureProvider,WXApiDelegate>
@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    
    [IQKeyboardManager sharedManager].enable = NO;
    [IQKeyboardManager sharedManager].enableAutoToolbar = NO;
    [IQKeyboardManager sharedManager].toolbarBarTintColor = [UIColor mi_1_color];
//    [IQKeyboardManager sharedManager].toolbarDoneBarButtonItemImage = [UIImage systemImageNamed:@"keyboard.chevron.compact.down"];
    [IQKeyboardManager sharedManager].toolbarDoneBarButtonItemImage = [UIImage imageNamed:@"icon_keyboard"];
    [IQKeyboardManager sharedManager].placeholderColor = UIColor.clearColor;
    
//    [application registerForRemoteNotifications];
    [self em_notification:application];
    
    [self initEaseIM];
    
    [UMConfigure initWithAppkey:UMAppkey channel:@"App Store"];
    
    [WXApi registerApp:WXAPPID universalLink:@"https://emmo/us/"];

    [self setupQCloud];
    [self setUserDefault];
    
    [self chargeIMLogin];
    
    [UIApplication sharedApplication].applicationIconBadgeNumber = 0;

    return YES;
}

- (void)initEaseIM {
    EMOptions *options = [EMOptions optionsWithAppkey:EMAppkey];
   
    options.apnsCertName = @"AuthKey_Dev";
    [[EMClient sharedClient] initializeSDKWithOptions:options];
    
    
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [EMClient.sharedClient.pushManager updatePushDisplayStyle:EMPushDisplayStyleMessageSummary completion:^(EMError * aError){
            if (aError) {
                NSLog(@"update display style error --- %@", aError.errorDescription);
            }
        }];
    });


    
    [USEaseIMHelper shareHelper];
}
- (void)chargeIMLogin {
    if (USUser.user.relStatus == 1 && USUser.user.loginStatus == YES) {
        if ([EMClient sharedClient].isLoggedIn == NO) {
            [[EMClient sharedClient] loginWithUsername:USUser.user.imUserName token:USUser.user.imToken completion:^(NSString * _Nonnull aUsername, EMError * _Nullable aError) {
                if (aError) {
                    NSLog(@"环信登录失败 ---- %li,%@",aError.code,aError);

                }else {
                    NSLog(@"环信登录成功");
                }
            }];
        }
     
    }
  
}

- (void)setUserDefault{
    
    [[NSUserDefaults standardUserDefaults]registerDefaults:@{
        
        USPrefKey_EnablePushNotification:@(YES),
        USPrefKey_EnableStartupGreeting:@(YES),
        USPrefKey_EnableFeedback:@(YES)        
    }];
    
}

- (void)setupQCloud{
    
    QCloudServiceConfiguration* configuration = [QCloudServiceConfiguration new];
    QCloudCOSXMLEndPoint* endpoint = [[QCloudCOSXMLEndPoint alloc] init];
    // 服务地域简称，例如广州地区是 ap-guangzhou
    endpoint.regionName = @"ap-shanghai";
    // 使用 HTTPS
    endpoint.useHTTPS = true;
    configuration.endpoint = endpoint;
    // 密钥提供者为自己
    configuration.signatureProvider = self;
    // 初始化 COS 服务示例
    [QCloudCOSXMLService registerDefaultCOSXMLWithConfiguration:configuration];
    [QCloudCOSTransferMangerService registerDefaultCOSTransferMangerWithConfiguration:
     configuration];
}

#pragma mark -  QCloudSignatureProvider

// 获取签名的方法入口，这里演示了获取临时密钥并计算签名的过程
// 您也可以自定义计算签名的过程
- (void) signatureWithFields:(QCloudSignatureFields*)fileds
                     request:(QCloudBizHTTPRequest*)request
                  urlRequest:(NSMutableURLRequest*)urlRequst
                   compelete:(QCloudHTTPAuthentationContinueBlock)continueBlock
{
    //SecretId: AKIDQbVDgmmQyDj12oc5WhjxQgCTkO4XF80w
    //SecretKey: uZq21vay83x8BOTJEvVxay6hYCc6Vi4c
    
    QCloudCredential* credential = [QCloudCredential new];
    credential.secretID = @"AKIDQbVDgmmQyDj12oc5WhjxQgCTkO4XF80w"; // 永久密钥 SecretId
    credential.secretKey = @"uZq21vay83x8BOTJEvVxay6hYCc6Vi4c"; // 永久密钥 SecretKey
    // 使用永久密钥计算签名
    QCloudAuthentationV5Creator* creator = [[QCloudAuthentationV5Creator alloc]
                                            initWithCredential:credential];
    QCloudSignature* signature = [creator signatureForData:urlRequst];
    continueBlock(signature, nil);
    
}


//当应用收到环信推送透传消息时，此方法会被调用。
- (void)emDidReceivePushSilentMessage:(NSDictionary *)messageDic{
    NSLog(@"emDidReceivePushSilentMessage : %@",messageDic);
}

- (void)em_notification:(UIApplication *)application{
    
    if (NSClassFromString(@"UNUserNotificationCenter")) {
        //注册推送，用于 iOS 10 及以上版本。
        [[UNUserNotificationCenter currentNotificationCenter] requestAuthorizationWithOptions:UNAuthorizationOptionBadge | UNAuthorizationOptionSound | UNAuthorizationOptionAlert completionHandler:^(BOOL granted, NSError *error) {
            if (granted) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    [application registerForRemoteNotifications];
                });
            }
        }];
        return;
    }
    
    [application registerForRemoteNotifications];
    
}
 


// 将获得的 deviceToken 传给 SDK。
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken{
    
    [[EMClient sharedClient] registerForRemoteNotificationsWithDeviceToken:deviceToken completion:^(EMError * _Nullable aError) {
        if (aError) {
            NSLog(@"bind deviceToken error: %@", aError.errorDescription);
        }
    }];
    
}
 
- (void)applicationDidEnterBackground:(UIApplication *)application{
    [[EMClient sharedClient] applicationDidEnterBackground:application];
}


- (void)applicationWillEnterForeground:(UIApplication *)application{
    [[EMClient sharedClient] applicationWillEnterForeground:application];
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // 清除角标
    [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
 
}
#pragma mark - UISceneSession lifecycle


- (UISceneConfiguration *)application:(UIApplication *)application configurationForConnectingSceneSession:(UISceneSession *)connectingSceneSession options:(UISceneConnectionOptions *)options {
    // Called when a new scene session is being created.
    // Use this method to select a configuration to create the new scene with.
    return [[UISceneConfiguration alloc] initWithName:@"Default Configuration" sessionRole:connectingSceneSession.role];
}


- (void)application:(UIApplication *)application didDiscardSceneSessions:(NSSet<UISceneSession *> *)sceneSessions {
    // Called when the user discards a scene session.
    // If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions.
    // Use this method to release any resources that were specific to the discarded scenes, as they will not return.
}


@end
